package com.atguigu.gmall.activity.controller;

import com.atguigu.gmall.activity.service.SeckillGoodsService;
import com.atguigu.gmall.activity.util.CacheHelper;
import com.atguigu.gmall.activity.util.DateUtil;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.model.activity.SeckillGoods;
import com.atguigu.gmall.model.activity.UserRecode;
import com.atguigu.gmall.rabbitmq.config.RabbitConst;
import com.atguigu.gmall.rabbitmq.service.RabbitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author: lx
 * @Time: 10:39
 * @Description:
 */
@RestController
@RequestMapping("/api/activity/seckill")
public class ActivityApiController {

    @Autowired
    private SeckillGoodsService seckillGoodsService;
    @Autowired
    private RabbitService rabbitService;
    //盐值
    private String salt = "fssfgsgfdgfsdsd";

    //获取抢购码
    @GetMapping("/auth/getSeckillSkuIdStr/{skuId}")
    public Result getSeckillSkuIdStr(@PathVariable Long skuId, HttpServletRequest request) {
        SeckillGoods seckillGoods = seckillGoodsService.getSeckillGoods(skuId);
//        1、要求商品必须在活动时间内
        Date startTime = seckillGoods.getStartTime();
        Date endTime = seckillGoods.getEndTime();
        Calendar instance = Calendar.getInstance();
        Date curTime = instance.getTime();

        //startTime <= curTime <= endTime 活动时间内  前面>后面=false  == 前面<=后面=true
        // startTime > curTime
        if (!DateUtil.dateCompare(startTime, curTime)) {
            return Result.build(null, ResultCodeEnum.SECKILL_NO_START);
        }
        //endTime <= curTime  活动结束了
        if (DateUtil.dateCompare(endTime, curTime)) {
            return Result.build(null, ResultCodeEnum.SECKILL_END);
        }
//        2、库存
        if (seckillGoods.getStockCount() <= 0) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
//        3、审核通过
        if (!seckillGoods.getStatus().equals("1")) {//硬编码问题
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
//        4、获取到抢购码
        String userId = AuthContextHolder.getUserId(request);
        String encrypt = MD5.encrypt(userId + skuId + salt);
//        5、Md5（userId+skuId+...)
//        6、好处：不用保存抢购码
        return Result.ok(encrypt);
    }

    //开始秒杀
    @PostMapping("/auth/seckillOrder/{skuId}")
    public Result seckillOrder(@PathVariable Long skuId, String skuIdStr, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
//        1、校验抢购码
        String encrypt = MD5.encrypt(userId + skuId + salt);
        if (!encrypt.equals(skuIdStr)) {
            return Result.build(null, ResultCodeEnum.SECKILL_ILLEGAL);
        }
//        2、状态位 skuId:0
//        本地内存
        String state = (String) CacheHelper.get(skuId.toString());
        if (!"1".equals(state)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FINISH);
        }
//        3、发消息  skuId userId
        UserRecode userRecode = new UserRecode();
        userRecode.setUserId(userId);
        userRecode.setSkuId(skuId);
        //发消息
        rabbitService.sendMessage(RabbitConst.EXCHANGE_DIRECT_SECKILL_USER,
                RabbitConst.ROUTING_SECKILL_USER, userRecode);
//        4.Result.oK
        return Result.ok();
    }

    //查询结果
    @GetMapping("/auth/checkOrder/{skuId}")
    public Result checkOrder(@PathVariable Long skuId, HttpServletRequest request) {
        String userId = AuthContextHolder.getUserId(request);
        //3:用户是否已经来过了
        Object o2 = redisTemplate.opsForValue().get(RedisConst.SECKILL_USER +
                userId + ":" + skuId);
        if (null != o2) {
            //1:查询是否已经下单了
            Object o = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS_USERS + userId);
            if (null != o) {
                return Result.build(null, ResultCodeEnum.SECKILL_ORDER_SUCCESS);
            }
            //2:查询是否有抢购资格
            Object o1 = redisTemplate.opsForValue().get(RedisConst.SECKILL_ORDERS + userId);
            if (null != o1) {
                return Result.build(null, ResultCodeEnum.SECKILL_SUCCESS);
            }
        }
        //4:状态位
        Object o3 = CacheHelper.get(skuId.toString());
        if (!"1".equals(o3)) {
            return Result.build(null, ResultCodeEnum.SECKILL_FAIL);
        }
        //排队中
        return Result.build(null, ResultCodeEnum.SECKILL_RUN);
    }

    @Autowired
    private RedisTemplate redisTemplate;
}
